package com.example.myapplication;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.myapplication.pojo.IotDataObj;
import com.example.myapplication.pojo.Res;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Environmental_Status_Activity extends AppCompatActivity {
    private Vibrator vibrator;
    private TextView ammonia1;
    private TextView ammonia2;

    private TextView fire1;
    private TextView fire2;

    private TextView smoke1;
    private TextView smoke2;

    private TextView hydrogen1;
    private TextView hydrogen2;

    private QMUITopBar mTopBar;

    private Handler handler;
    private Runnable runnable;
    private static final int POLLING_INTERVAL = 5000; // 轮询间隔时间，单位为毫秒
    private static final String CHANNEL_ID = "channel_id_1";
    int flag=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_environmental_status);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mTopBar=findViewById(R.id.e_stopbar);
        QMUIStatusBarHelper.translucent(this);// 沉浸式状态栏
        initTopBar();//初始化状态栏
        ammonia1=findViewById(R.id.ammonia_status1);
        ammonia2=findViewById(R.id.ammonia_status2);
        fire1=findViewById(R.id.fire_status1);
        fire2=findViewById(R.id.fire_status2);
        smoke1=findViewById(R.id.smoke_status1);
        smoke2=findViewById(R.id.smoke_status2);
        hydrogen1=findViewById(R.id.hydrogen_status1);
        hydrogen2=findViewById(R.id.hydrogen_status2);
//        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//            NotificationChannel notificationChannel = new NotificationChannel("id1", "name", NotificationManager.IMPORTANCE_HIGH);
//            if (manager != null) {
//                manager.createNotificationChannel(notificationChannel);
//            }
//        }
//
//        Notification notification = new NotificationCompat.Builder(this, "id1")
//                .setContentTitle("title")
//                .setContentText("内容")
//                .setWhen(System.currentTimeMillis())
//                .setSmallIcon(R.drawable.pm)
////                .setLargeIcon(R.drawable.pm)
//                .setAutoCancel(true)
//                .build();
//        manager.notify(1,notification);


        vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);




        updatedata();
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                // 在这里执行你的网络请求操作
                new MyAsyncTask().execute();
                // 请求完成后，延迟一段时间再次发送请求
                handler.postDelayed(this, POLLING_INTERVAL);
            }
        };

        handler.post(runnable); // 启动轮询
    }

    private class MyAsyncTask extends AsyncTask<Void, Void, IotDataObj> {

        @Override
        protected IotDataObj doInBackground(Void... voids) {
            // 执行你的异步网络请求操作

            updatedata();

            // 返回请求结果，比如请求到的数据字符串
            return null;
        }

        @Override
        protected void onPostExecute(IotDataObj iotDataObj) {
            // 在UI线程更新UI
//            Temperature.setText(iotDataObj.getTemperature().toString()+"°C");
//            Humidity.setText(iotDataObj.getHumidity().toString()+"%");
//            hyVal.setText(iotDataObj.getHyVal().toString()+"pa");
//            amVal.setText(iotDataObj.getAmVal().toString()+"Lux");
//            dustVal.setText(iotDataObj.getDustVal().toString()+"ppm");
//            time.setText(iotDataObj.getTimestamp().toString());
        }
    }
    private void updatedata(){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("http://101.34.248.186:8084/iot/getcurrentdata")
                .method("GET", null)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.i("lxl",e.getMessage());
                Log.i("lxl","error");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.i("lxl","success");
                String res = response.body().string();
                Res r = JSON.parseObject(res, Res.class);
                IotDataObj iotDataObj = JSON.parseObject(r.getData().toString(), IotDataObj.class);

//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (iotDataObj.getAmmonia_warning().equals("ON")){
//                            flag=1;
//                            ammonia1.setText("异常");
//                            ammonia1.setTextColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.red));
//                            ammonia2.setBackgroundColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.red));
//                        }else{
//                            ammonia1.setText("正常");
//                            ammonia1.setTextColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.green));
//                            ammonia2.setBackgroundColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.green));
//                        }
//
//                        if (iotDataObj.getHydrogen_warning().equals("ON")){
//                            flag=1;
//                            hydrogen1.setText("异常");
//                            hydrogen1.setTextColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.red));
//                            hydrogen2.setBackgroundColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.red));
//                        }else{
//                            hydrogen1.setText("正常");
//                            hydrogen1.setTextColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.green));
//                            hydrogen2.setBackgroundColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.green));
//                        }
//
//                        if (iotDataObj.getFire_Warning().equals("ON")){
//                            flag=1;
//                            fire1.setText("异常");
//                            fire1.setTextColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.red));
//                            fire2.setBackgroundColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.red));
//                        }else{
//                            fire1.setText("正常");
//                            fire1.setTextColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.green));
//                            fire2.setBackgroundColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.green));
//                        }
//
//                        if (iotDataObj.getSmoke_Warning().equals("ON")){
//                            flag=1;
//                            smoke1.setText("异常");
//                            smoke1.setTextColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.red));
//                            smoke2.setBackgroundColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.red));
//                        }else{
//                            smoke1.setText("正常");
//                            smoke1.setTextColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.green));
//                            smoke2.setBackgroundColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.green));
//                        }
//                        if (flag==1){
//                            flag=0;
//                            showNotification();
//                            long[] pattern = { 1000L, 1000L }; // 关 1000 毫秒，开 1000 毫秒
//                            vibrator.vibrate(pattern, 0); // 0 代表从 pattern 数组的索引 0 开始循环
//                        }
//                    }
//                });

            }
        });

    }
    private void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.blue));
        mTopBar.setTitleGravity(Gravity.LEFT);
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vibrator.cancel();
                finish();
            }
        });

        mTopBar.setTitle("环境状态");
    }

    private void showNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "My Channel",
                    NotificationManager.IMPORTANCE_HIGH
            );
            channel.setDescription("My notification channel");
            channel.enableLights(true);
            channel.setLightColor(Color.RED);
            manager.createNotificationChannel(channel);
        }

        Intent intent = new Intent(this, Current_Environment_Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Warning!")
                .setContentText("There is a importance warning.")
                .setSmallIcon(R.drawable.warning)
                .setDefaults(Notification.DEFAULT_VIBRATE)  // 使用默认的振动模式
                .setColor(ContextCompat.getColor(Environmental_Status_Activity.this, R.color.red))
                .setContentIntent(pendingIntent) // Set the PendingIntent
                .setAutoCancel(true)
                .build();

        manager.notify(1, notification);
    }
    @Override
    protected void onPause(){
        super.onPause();
        vibrator.cancel();
    }
}